package juc.atomic;

import juc.factory.UnsafeFactory;
import sun.misc.Unsafe;

public class CASTest {

    public static void main(String[] args) {

        Entity entity = new Entity();
        Unsafe unsafe = UnsafeFactory.getUnsafe();
        boolean successful;
        //获取偏移量
        long offset = UnsafeFactory.getFieldOffset(unsafe,Entity.class, "x");
        //四个参数:对象实例、字段的内存偏移量、字段期望值、字段更新值
        successful = unsafe.compareAndSwapInt(entity, offset, 0, 3);
        System.out.println(successful+"\t"+entity.x);
        successful = unsafe.compareAndSwapInt(entity, offset, 3, 5);
        System.out.println(successful+"\t"+entity.x);
        successful = unsafe.compareAndSwapInt(entity, offset, 3, 8);
        System.out.println(successful+"\t"+entity.x);

    }

}

class Entity{
    int x;
}
